import os
import urllib
import ddddocr
import requests
from bs4 import BeautifulSoup

METHOD = 'POST'
LOGIN_URL = 'https://so.gushiwen.cn/user/login.aspx?from=http%3a%2f%2fso.gushiwen.cn%2fuser%2fcollect.aspx'
BASE_URL = 'https://so.gushiwen.cn/user/login.aspx'
HEADER = {
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) '
                  'AppleWebKit/537.36 (KHTML, like Gecko) '
                  'Chrome/103.0.0.0 Safari/537.36'
}
FORM_DATA = {
    'email': '1791255334@qq.com',
    'pwd': 'DZZ19970906',
    'denglu': '登录',
    'from': 'http://so.gushiwen.cn/user/collect.aspx'
}

LOGIN_SESSION = requests.session()
# 首先获取登录页面
response = LOGIN_SESSION.get(url=BASE_URL, headers=HEADER)
response.encoding = 'UTF-8'
LOGIN_PAGE = response.text
# print(LOGIN_PAGE)
soupObject = BeautifulSoup(LOGIN_PAGE, 'lxml')

# 得到登陆接口的随机生成参数
VIEW_STATE = soupObject.select_one(selector='#__VIEWSTATE').attrs.get('value')
VIEW_STATE_GENERATOR = soupObject.select_one(selector='#__VIEWSTATEGENERATOR').attrs.get('value')
FORM_DATA['__VIEWSTATE'] = VIEW_STATE
FORM_DATA['__VIEWSTATEGENERATOR'] = VIEW_STATE_GENERATOR

# 获取图片验证码
CAPTCHA_FILE_NAME = 'captcha.png'
CAPTCHA_URL = 'https://so.gushiwen.cn' + soupObject.select_one(selector='#imgCode').attrs.get('src')

# 改用一次会话中的请求，让服务认为这是一个请求之内的
CAPTCHA_DATA = LOGIN_SESSION.get(CAPTCHA_URL)

# 解析码值， 入参是验证码图片的二进制数据
ocr = ddddocr.DdddOcr()
CAPTCHA_CODE = ocr.classification(CAPTCHA_DATA.content)
FORM_DATA['code'] = CAPTCHA_CODE

# 开始执行登录操作
LOGIN_RESULT = LOGIN_SESSION.post(url=LOGIN_URL, headers=HEADER, data=FORM_DATA)
USER_PAGE = LOGIN_RESULT.text

print(response.headers)

# 把结果输出到文件里
# with open('./user-page.html', 'w', encoding='UTF-8') as fp:
#     fp.write(USER_PAGE)


